package br.com.cardoso.videostore.web.jsf;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.cardoso.application.ApplicationConstants;
import org.cardoso.web.jsf.ManagedBeanBasic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import br.com.cardoso.videostore.model.entity.UserEntity;
import br.com.cardoso.videostore.persistence.IUserPersistence;

@ManagedBean(name = "authenticationMB")
@ViewScoped
public class AuthenticationMB extends ManagedBeanBasic<UserEntity> {

	private static final long serialVersionUID = 1L;
	
	@Autowired
	@Qualifier("userPersistence")
	private IUserPersistence persistence;
	
	public AuthenticationMB() {
		super(UserEntity.class);
		initComponents();
	}
	
	public void authenticate() {
		try {
			UserEntity userLogged = getPersistence().getUser(getEntity().getUserName(), getEntity().getPassword());
			if (userLogged != null) {
				setSessionAttribute(ApplicationConstants.USER_LOGGED, userLogged);
				sendRedirect("index.html");
			}
			addMessage("Usuário ou senha incorretos.", SEVERITY_ERROR);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected IUserPersistence getPersistence() {
		return persistence;
	}
	
	@Override
	public UserEntity getEntity() {
		return (UserEntity) super.getEntity();
	}
	
	public void setEntity(UserEntity userEntity) {
		super.setEntity(userEntity);
	}

}